import React, { Component } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { Form, Input, Button, notification, Icon, Select, Col, Row, Cascader, DatePicker, message, Modal, Radio, Switch } from 'antd';
import { FormComponentProps } from "antd/lib/form/Form";
import OneItem from './OneItem'

import { DICT } from '../enum'
import { DropDownSelect, DropDownSelectList } from '@/components/DropDownSelect/index';
import { judgeAreaFn } from '@/utils/judgeArea';
import styles from '@/styled/form.less';
import Imgviewer from '@/components/ImgViewer';
import PropertyModal from './PropertyModal';
import { checkNoChinese, checkNoNumAndSym } from '@/utils/inputCheck'
import MapSelet from '@/components/MapSelect';
import { MyButton } from '../styled';

import { DividerItem } from '@/components/DividerItem';
import { inject_unount } from '@/utils/middleware';

const { Option } = Select;
const { TextArea } = Input;
interface Props extends FormComponentProps {
  dispatch?: any;
  data: {
    id?: number,
    x?: number,
    y?: number,
    name: string,
    image?: string,
    areaId?: number,
    relationUserPhone: string;
    areaName?: string,
    ownerCode: number,
    mobile?: string;
    registerTime?: string,
    bindStatus?: String,
    onlyTask?: String,
    autoCall?: String,
    chemical?: String,
    industryType?: string,
    relationId?: string,
    relationUser?: string,
    propertyOwnerName: string,
    propertyOwnerId: string;
    economicType: string;
    peopleScale: string;
    asset: string;
    floorSpace: string;
    postalCode: string;
    trade: string;
  },
  img?: {
    url: string,
    message: string,
  },
  keys?: Array<string>,
  dict?: any,
  provice?: Array<any>,
  sub?: Array<any>,
  relationList?: Array<any>,
  ownerList?: Array<any>,
  propertyList?: Array<any>,
}

@inject_unount
@connect(({ owner, location, upload }) => ({
  dict: owner.dict || {},
  img: upload.imgValue,
  provice: location.provice,
  sub: location.sub,
  relationList: owner.relationList || [],
  propertyList: owner.newPropertyList || [],
  ownerList: owner.ownerList || [],
}))
class FormItem extends Component<Props, any> {
  state = {
    isNew: true,
    visible: false,
    isShow: false,
    propertyVisible: false,
    option: [],
    propertyOwnerName: '',
    areaList: [],
    areaId: '',
    areaName: '',
    relationUser: '',
    relationId: '',
    relationInd: null,
    submitConfirm: false,
    image: '',
    position: '',
    tmpLocation: null,
    name: ''
  };

  componentDidMount() {
    const { data, form, dispatch } = this.props;

    dispatch({
      type: 'owner/init', payload: {
        dict: { keyList: DICT },
        url: data ? data.image : null
      }
    }).then(() => {
      const { provice } = this.props;
      this.setState({ option: provice })
    })
    if (data) {
      const params = {
        industryType: data.industryType,
        areaId: data.areaId,
      };

      const { name, id, relationId, relationUser, relationUserPhone, bindStatus, x, y, ownerCode, image, onlyTask,
        registerTime, areaId, areaName, propertyOwnerName, autoCall, ...items } = data;

      const must = {
        registerTime,
        propertyOwnerId: items.propertyOwnerId,
        economicType: items.economicType,
        peopleScale: items.peopleScale,
        asset: items.asset,
        floorSpace: items.floorSpace,
        trade: items.trade,
        ownerCode,
        postalCode: items.postalCode,
      }

      if (+bindStatus) {
        !relationId ? notification['warning']({
          message: `请重新选择主管部门`,
          description: '原主管部门不在选择范围内,请重新选择',
        }) : this.queryRelationList(params)
      }

      const ans = {
        name,
        ...(+bindStatus ? {
          relationId,
          relationUser: `${relationUser}/${relationUserPhone}`,
        } : {}),
        registerTime: registerTime ? moment(registerTime, 'YYYY-MM-DD') : null,
        onlyTask: +onlyTask,
        bindStatus: +bindStatus,
        autoCall: +autoCall,
        ownerCode,
        ...items
      };

      this.setState({
        areaName,
        areaId,
        image,
        name,
        position: `${x || ''},${y || ''}`,
        propertyOwnerName,
        isShow: Object.values(must).some(v => !!v)
      }, () => form.setFieldsValue(ans));
    }
  }

  uploadImage(e) {
    e.persist();
    const { dispatch } = this.props;
    const file = e.target.files[0];
    dispatch({ type: 'upload/uploadImg', payload: file });
  }


  queryRelationList = (params) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'owner/queryRelationList',
      payload: params
    }).then(() => {
      const { data } = this.props;
      data && this.props.form.setFieldsValue({
        relationId: data.relationId,
        relationUser: `${data.relationUser}/${data.relationUserPhone}`
      })
    })
  }

  onSelectIndus = (value) => {
    const params = {
      industryType: value,
      areaId: this.state.areaId,
    }
    this.queryRelationList(params);
  }

  setProperty(data) {
    if (data && data.id) {
      const { form } = this.props;
      form.setFieldsValue({ propertyOwnerId: data.id })
    }
    this.setState({ propertyVisible: false, propertyOwnerName: data && data.name ? data.name : '' })
  }

  handleSubmit = (e) => {
    e.preventDefault();

    const { dispatch, form, data, img, ownerList = [] } = this.props;
    const { relationUser, position } = this.state;

    form.validateFields((err, values) => {

      if (!err) {
        const { areaId, registerTime, relationUserPhone, safetySystemTime, onlyTask, bindStatus, autoCall, ...res } = values;
        if (areaId && Array.isArray(areaId) && areaId.length < 4) {
          message.warning('该所属区域不可用，请选择至街道', 1);
          return;
        }
        const ans = {
          ...res,
          x: position ? position.split(',')[0] : null,
          y: position ? position.split(',')[1] : null,
          image: img.url,
          bindStatus: bindStatus ? 1 : 0,
          onlyTask: onlyTask ? 1 : 0,
          relationUser: bindStatus && ownerList[+relationUser] ? ownerList[+relationUser].realName : (data ? data.relationUser : ''),
          relationUserPhone: bindStatus && ownerList[+relationUser] ? ownerList[+relationUser].mobile : (data ? data.mobile : ''),
          registerTime: values.registerTime ? moment(values.registerTime).format("YYYY-MM-DD HH:mm:ss") : null,
        };

        ans['areaId'] = judgeAreaFn(message, this.state.areaList, this.state.areaId);
        if (ans['areaId'] === false) {
          return;
        }

        data && data.id ? dispatch({
          type: 'owner/update',
          payload: {
            id: data.id,
            ...ans
          }
        }) : dispatch({
          type: 'owner/create',
          payload: {
            ...ans
          }
        })

      } else {
        notification['error']({
          message: `保存失败`,
          description: '单位信息录入不规范',
        });
      }
    })
  };

  onSelect = (id) => {
    const { dispatch, form } = this.props;


    dispatch({
      type: 'owner/queryOwnerList',
      payload: {
        companyId: id
      }
    }).then(() => {
      this.setState({ relationId: id }, () => {
        form.resetFields(['relationUser'])
      });
    })
  }

  selectPerson = (value) => {
    this.setState({ relationUser: value },
      () => this.props.form.setFieldsValue({ relationUserPhone: value })
    );
  }

  onChangeCascader = (value) => {
    const { form } = this.props;
    const areaId = Array.isArray(value) && value.length > 0 ? value[value.length - 1] : '';
    const params = {
      industryType: form.getFieldValue('industryType'),
      areaId: areaId,
    }
    this.queryRelationList(params);

    this.setState({
      areaList: value,
      areaId,
    })
  };

  handleProperty = () => {
    const { dispatch } = this.props;
    dispatch({ type: 'owner/queryPropertyPage', payload: { pageSize: 10, pageNum: 1 } }).then(() => {
      this.setState({
        propertyVisible: true
      })
    })
  }

  loadData = (selectedOptions) => {
    const { dispatch, provice } = this.props;
    const targetOption = selectedOptions[selectedOptions.length - 1];
    targetOption.loading = true;

    if (+targetOption.value < 1e8) {
      dispatch({ type: 'location/querySubordinate', payload: targetOption.value }).then(() => {
        targetOption.loading = false;
        targetOption.children = this.props.sub;
        const op = this.state.option || provice;
        this.setState({
          option: [...op],
        });
      })
    }
  }

  handleShow = v => {
    this.setState({ isShow: v })
  }

  render() {
    const { form, data = { id: '', industryType: '' }, dict = {}, relationList, ownerList, img } = this.props;
    const { getFieldDecorator, getFieldValue } = form;
    const { visible, isShow } = this.state;
    const bindStatus = getFieldValue('bindStatus');

    const formItemLayout = {
      labelCol: {
        xs: { span: 12 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 6 },
        sm: { span: 14 },
      },
    };

    const textAreaLayout = {
      labelCol: { span: 3 },
      wrapperCol: { span: 19 },
    };

    const Info = DividerItem("reconciliation", '基础信息')

    const ButtonList = () => (
      <Form.Item>
        <Button style={{ marginLeft: 20 }} onClick={() => {
          window.history.back()
        }}>取消</Button>
        <Button type="primary"
          htmlType="submit"
          style={{ marginLeft: 20 }}
          onClick={(e) => {
            data ? this.handleSubmit(e) : this.setState({ submitConfirm: true })
          }}
        >保存</Button>
      </Form.Item>
    )

    const Contact = DividerItem("idcard", '联系方式')

    const Details = DividerItem("appstore", '详细信息', true, isShow, this.handleShow)

    const Position = DividerItem('monitor', '功能配置')

    return (
      <Form>
        <Info />
        <Row>
          <Col span={8}>
            <OneItem title='单位名称' require={true} type='name' form={form} />
          </Col>
          <Col span={8}>
            <Form.Item
              {...formItemLayout}
              label='所属区域'
              className={styles.fileRequire}
            >
              {getFieldDecorator('areaId')(
                <Cascader
                  options={this.state.option || this.props.provice}
                  loadData={this.loadData}
                  changeOnSelect
                  placeholder={this.state.areaName || '请选择'}
                  onChange={this.onChangeCascader}
                />
              )}
            </Form.Item>
          </Col>
          <Col span={8}>
            <OneItem title='详细地址' require={true} type='address' form={form} />
          </Col>
        </Row>
        <Row>
          <Col span={8}>
            <Form.Item
              {...formItemLayout}
              label='监管类别'
            >
              {getFieldDecorator('flag', {
                rules: [{ required: true, message: '请选择监管类别', whitespace: true }],
              })(
                (DropDownSelect(dict, 'owner.flag'))
              )}
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              {...formItemLayout}
              label='单位类别'
            >
              {getFieldDecorator('type', {
                rules: [{ required: true, message: '请选择单位类别', whitespace: true }],
              })(
                (DropDownSelect(dict, 'owner.type'))
              )}
            </Form.Item>
          </Col>

          <Col span={8}>
            <Form.Item
              {...formItemLayout}
              label='单位坐标'
              className={styles.fileRequire}
            >
              <MyButton onClick={() => this.setState({ visible: true })}>
                <Icon type="environment" />地图坐标</MyButton>
              <span style={{ display: 'inline-block', marginLeft: '5px' }}>{this.state.position}</span>
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col span={16} >
            <Form.Item
              {...textAreaLayout}
              label='单位简介'
              className={styles.fileRequire}
            >
              {getFieldDecorator('intro', {
                rules: [{
                  required: true, message: '请输入简介', whitespace: true
                }, {
                  type: 'string', max: 288, message: '不可超过144个数字'
                }],
              })(
                <TextArea title='单位简介' rows={4} />
              )}
            </Form.Item>
          </Col>
          <Col span={8} >
            <Form.Item
              {...formItemLayout}
              label='单位图片'
              className={styles.fileRequire}
            >
              <input
                style={{ opacity: 0, width: 120, zIndex: 10, position: 'absolute', cursor: 'pointer' }}
                onChange={(e) => { this.uploadImage(e) }} type="file" accept="image/*"
              />
              <MyButton style={{ marginTop: -50, marginRight: 10 }}>
                <Icon type="upload" />
                 上传图片
                </MyButton>
              <Imgviewer hasText="查看平面图" missText="暂无平面图" url={img.url} />
            </Form.Item>
            <Form.Item
              {...formItemLayout}
              label='是否涉及化学品'
            >
              {getFieldDecorator('chemical')(
                <Radio.Group>
                  <Radio value={1}>是</Radio>
                  <Radio value={0}>否</Radio>
                </Radio.Group>
              )}
            </Form.Item>
          </Col>
        </Row>
        <Position />

        <Row>
          <Col span={8}>
            <Form.Item
              {...formItemLayout}
              label='单位消防评定'
            >
              {getFieldDecorator('bindStatus', { valuePropName: 'checked' })(
                <Switch />
              )}
            </Form.Item>
          </Col>
          {/* {bindStatus} */}
          {
            !!bindStatus && <>
              <Col span={8}>
                <Form.Item
                  {...formItemLayout}
                  label='监管政府'
                >
                  {getFieldDecorator('relationId', {
                    rules: [{ required: true, message: '请选择' }],
                  })(
                    DropDownSelectList(relationList, '', '100%', this.onSelect)
                  )}
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item
                  {...formItemLayout}
                  label='监管负责人'
                >
                  {getFieldDecorator('relationUser', {
                    rules: [{ required: true, message: '请选择监管负责人' }],
                  })(
                    <Select onChange={this.selectPerson}>
                      {Array.isArray(ownerList) && ownerList.map((item, ind) => {
                        return <Option key={ind}>{item.realName} / {item.mobile}</Option>
                      })}
                    </Select>
                  )}
                </Form.Item>
              </Col>
            </>
          }
        </Row>
        <Row>
          <Col span={8}>
            <Form.Item
              {...formItemLayout}
              label='单位巡检'
            >
              {getFieldDecorator('onlyTask', { valuePropName: 'checked' })(
                <Switch />
              )}
            </Form.Item>
          </Col>
          <Col span={16}></Col>
        </Row>
        <Contact />
        <Row>
          <Col span={8}>
            <OneItem title='消防责任人' require={true} type='corporation' form={form}
              validator={checkNoNumAndSym}
            />
          </Col>
          <Col span={8}>
            <OneItem title='责任人电话' require={true} type='corporationMobile' form={form} />
          </Col>
          <Col span={8}>
            <OneItem title='责任人身份证' type='corporationIdCard' form={form} />
          </Col>
        </Row>
        <Row>
          <Col span={8}>
            <OneItem title='消防管理人' require={true} type='proFireManagerName' form={form}
              validator={checkNoNumAndSym}
            />
          </Col>
          <Col span={8}>
            <OneItem title='管理人电话' require={true} type='proFireManagerMobile' form={form} />
          </Col>
          <Col span={8}>
            <OneItem title='管理人身份证' type='proFireManagerIdCard' form={form} />
          </Col>
        </Row>
        <Details />
        <span style={{ height: `${isShow ? '230px' : '0px'}`, overflow: 'hidden', display: 'block' }}>
          <Row>
            <Col span={8}>
              <Form.Item {...formItemLayout} label="成立时间">
                {getFieldDecorator('registerTime', {
                  rules: [{ required: false, message: '请选择' }],
                })(
                  <DatePicker {...getFieldDecorator('registerTime')} placeholder="选择成立时间" style={{ width: '95%' }} />
                )}
              </Form.Item>
            </Col>
            <Col span={8}>
              <OneItem title='单位邮编' require={false} type='postalCode' form={form}
                validator={checkNoChinese}
              />
            </Col>

            <Col span={8}>
              <Form.Item
                {...formItemLayout}
                label='单位代码'
              >
                {getFieldDecorator('ownerCode')(
                  (DropDownSelect(dict, 'owner.code'))
                )}
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col span={8}>
              <Form.Item
                {...formItemLayout}
                label='占地面积'
              >
                {getFieldDecorator('floorSpace',
                  { rules: [{ validator: checkNoChinese }] }
                )(
                  <Input style={{ width: '100%' }} placeholder='请输入' addonAfter="m²" />
                )}
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                {...formItemLayout}
                label='固定资产'
              >
                {getFieldDecorator('asset',
                  { rules: [{ validator: checkNoChinese }] }
                )(
                  <Input style={{ width: '100%' }} placeholder='固定资产' addonAfter="万" />
                )}
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                {...formItemLayout}
                label='职工人数'
              >
                {getFieldDecorator('peopleScale',
                  { rules: [{ validator: checkNoChinese }] }
                )(
                  <Input style={{ width: '100%' }} placeholder='请输入' addonAfter="人" />
                )}
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col span={8}>
              <Form.Item
                {...formItemLayout}
                label='经济类型'
              >
                {getFieldDecorator('economicType')(
                  DropDownSelect(dict, 'economic.type')
                )}
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                {...formItemLayout}
                label='所属行业'
              >
                {getFieldDecorator('industryType', {
                  rules: [{ message: '请选择行业类型', whitespace: true }],
                })(
                  (DropDownSelect(dict, 'owner.fire.industry.type', null, null,
                    '请选择行业类型', null, data.id && data.industryType ? true : false,
                    this.onSelectIndus
                  ))
                )}
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                {...formItemLayout}
                label='所属物业'
              >
                {getFieldDecorator('propertyOwnerId')(
                  <Input style={{ display: 'none' }} placeholder='请选择物业单位' disabled />
                )}
                <MyButton onClick={this.handleProperty}>
                  <Icon type="check-circle" />选择物业</MyButton>
                <span style={{ display: 'inline-block', marginLeft: '5px' }}>{this.state.propertyOwnerName}</span>
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col span={8}>
              <Form.Item
                {...formItemLayout}
                label='行业类别'
              >
                {getFieldDecorator('trade', {
                  rules: [{  message: '请选择行业类别', whitespace: true }],
                })(
                  (DropDownSelect(dict, 'owner.trade'))
                )}
              </Form.Item>
            </Col>
          </Row>
        </span>
        <Row><ButtonList /></Row>
        <Modal
          visible={visible}
          title="地图坐标"
          width={960}
          okText="保存"
          onCancel={() => this.setState({ visible: false, tmpLocation: null })}
          onOk={() =>
            this.setState({
              position: Array.isArray(this.state.tmpLocation) ? this.state.tmpLocation.join(',') : '',
              visible: false
            })}
        >
          <MapSelet
            name={this.state.name}
            location={this.state.position ? this.state.position.split(',') : []}
            setPoint={v => this.setState({ tmpLocation: v })}
          />
        </Modal>
        <PropertyModal
          visible={this.state.propertyVisible}
          cancelProperty={() => this.setState({ propertyVisible: false })}
          setProperty={(data) => this.setProperty(data)}
        />
      </Form >
    );
  }
}

const FormList = Form.create<Props>()(FormItem);
export default FormList;
